package org.adorsys.aderp.jpa.impl;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.util.ReflectionUtils;

/**
 * The one to many field is generally a collection.
 * 
 * If a mapKey Annotation is available, then it is a map.
 * 
 * In this version we will handle only Collection types.
 *  
 * @author francis
 *
 */
public class OneToManyRelationShipInfo extends RepositoryResolver{

//	private final Field field;
	private final Method getterMethod;

	public OneToManyRelationShipInfo(Field field, Method getterMethod,
			BeanFactory beanFactory, Class<?> jpaKlass) {
		super(beanFactory, jpaKlass);
//		this.field = field;
		this.getterMethod = getterMethod;
	}

	/**
	 * We will not change the entity collection. We assume it is not an unmodifiable collection.
	 * 
	 * @param target
	 */
	@SuppressWarnings("unchecked")
	public <T> void attachField(Object target){
		Collection<T> collection = (Collection<T>) ReflectionUtils.invokeMethod(getterMethod, target);
		if(collection==null) return;
		Collection<T> newColl = new ArrayList<T>();
		for (T object : collection) {
			T attached = (T) getRepository().findByBusinessKey(object);
			if(attached!=null)
				newColl.add(attached);
		}
		collection.clear();
		collection.addAll(newColl);
	}
}
